package com.leon.config;

import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class DbConnectionConfig {

    private String zkServer = "127.0.0.1:2181";
    private String rootPath = "/dynamic-db/db-node";

    /**
     * 从 zk 中获取数据库连接信息并监控 zk 节点,当内容发生变化时, 重新构建数据库连接池
     */
    @PostConstruct
    public void initDBConnection() throws Exception {
        // 获取 zk 客户端工具
        ZkClient zkClient = new ZkClient(zkServer);
        Object data = zkClient.readData(rootPath);
        if (data == null) {
            throw new Exception("no valid mysql connection info");
        }
        // zk 中存储的的格式为 url,username,password, 如: jdbc:mysql://127.0.0.1:13306/nnm5,root,root
        String[] info = data.toString().split(",");
        DBEntity entity = new DBEntity();
        entity.setUrl(info[0]);
        entity.setUserName(info[1]);
        entity.setPassword(info[2]);

        DbConnectionManager.initManager(entity);

        // 对指定节点进行数据变更监听, 有变动就重新构建数据库连接池
        zkClient.subscribeDataChanges(rootPath, new IZkDataListener() {
            @Override
            public void handleDataChange(String s, Object o) throws Exception {
                String[] info = o.toString().split(",");
                DBEntity entity = new DBEntity();
                entity.setUrl(info[0]);
                entity.setUserName(info[1]);
                entity.setPassword(info[2]);
                DbConnectionManager.refreshPool(entity);
            }

            @Override
            public void handleDataDeleted(String s) throws Exception {}
        });

    }

}
